package com.lwq.springbootdruid.aop;

import com.lwq.springbootdruid.entity.MyLog;
import com.lwq.springbootdruid.service.MyLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lwq.springbootdruid.utils.LogUtils;
import com.lwq.springbootdruid.utils.MyRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author liwq
 * @description
 * @date 2021/7/15 10:07
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    @Autowired
    private MyLogService myLogService;

    @Pointcut("@annotation(com.lwq.springbootdruid.annotation.MyLogAnnotation)")
    public void logPoint() {}

    @Before("logPoint()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        log.info("执行doAround()=========================================开始");
        // 记录方法的执行时间
        currentTime.set(System.currentTimeMillis());
        // 定义日志类型
        MyLog myLog = new MyLog();
        myLog.setType("INFO");
        myLog.setTime(System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        myLog.setUserName("admin");
        HttpServletRequest request = MyRequest.getHttpServletRequest();
        myLog.setBrowser(LogUtils.getBrowser(request));
        myLog.setIp(LogUtils.getIp(request));
        myLog.setDescription("测试");
        myLog.setParams("测试参数");
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        myLog.setMethod(method.getName());
        myLog.setExceptionDetail("测试异常");
        myLogService.save(myLog);
        log.info("执行doAround()=========================================结束");
    }

}
